<?php
namespace app\admin\model;
use app\common\model\WebSet as WebSetModel;
use app\common\library\mstching\YiLian;
use think\Cache;

/**
 * 系统设置模型
 */
class WebSet extends WebSetModel
{
    /**
     * 设置项描述
     */
    private $describe = [
        'web' => '站点设置',
		'register' => '注册设置',
		'delivery' => '配送接口',
		'pay' => '收款设置',
		'wxapp' => '商户手机端',
		'printer' => '打印设备',
		'menus' => '公众号菜单',
		'tplmsg' => '模板消息',
		'subscribe' => '关注回复',//公众号
		'invalid' => '无效回复',//公众号
    ];

    /**
     * 更新系统设置
     */
    public function edit($key, $values)
    {
		if($key == 'menus'){
			$result = $this->creatmMenu($values);
			if($result['errcode']!=0){
				$this->error = '同步失败,错误代码：'.$result['errcode'].'错误说明：'.$result['errmsg'];
				return false;
			}
		}
		//打印机配置
		if($key == 'printer'){
			//易联云获取token
			if(empty($values['yilian']['access_token'])){
				if((!empty($values['yilian']['app_key'])) AND (!empty($values['yilian']['app_secret']))){
					$client = new YiLian();
					$values['yilian']['access_token'] = $client->getToken($values['yilian']['app_key'],$values['yilian']['app_secret']);
				}
			}
		}
        $model = self::detail($key) ?: $this;
        // 删除系统设置缓存
        Cache::rm('web_set_hema');
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
        ]) !== false;
    }
	
	/**
	* 自定义菜单 - 同步到微信端
	*/
	private function creatmMenu($menu){
		$access_token = getAccessToken('',0);
		$menu = json_encode($menu,JSON_UNESCAPED_UNICODE);
		$url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
		$data = '{"button":'.$menu.'}';
		return json_decode(http_request($url,$data),true);
	}
}
